package cn.yunyichina.provider.hquery.thread;

import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.hquery.dao.InspectDao;
import cn.yunyichina.provider.hquery.dao.InspectDetailDao;
import cn.yunyichina.provider.hquery.entity.Inspect;
import cn.yunyichina.provider.hquery.entity.InspectDetail;
import cn.yunyichina.provider.hquery.vo.ExaminationVo;
import cn.yunyichina.provider.iface.entity.base.MedicalCardVo;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.hisiface.examination.InspectDetailVoResponse;
import cn.yunyichina.provider.iface.entity.hisiface.examination.InspectListVoResponse;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 15-AK on 2016/12/15.
 */
public class InspectListAndDetailRunnable  implements Runnable{
	
    private static final Logger logger = LoggerFactory.getLogger(InspectListAndDetailRunnable.class);
    
    private List<InspectListVoResponse> inspectListVoResponseList;
    
    private ExaminationVo requestVo;
    
    private InspectDao inspectDao = SpringContextHandler.getBean(InspectDao.class);
    
    private InspectDetailDao inspectDetailDao = SpringContextHandler.getBean(InspectDetailDao.class);
    
    public InspectListAndDetailRunnable(List<InspectListVoResponse> inspectListVoResponseList,ExaminationVo requestVo) {
        this.inspectListVoResponseList = inspectListVoResponseList;
        this.requestVo = requestVo;
    }

    @Override
    public void run() {

        logger.info("保存检验列表和明细记录开始======inspectListVoResponseList ="+JsonUtils.toJsonString(inspectListVoResponseList));
        
        //查询绑定卡
        logger.info("【检验列表和明细保存线程处理-查询绑定卡信息】, yyt.base.medicalcard.by.id.get request=" + JSONObject.toJSONString(requestVo));
        MedicalCardVo medicalCard =  BaseService.getMedicalCardByCardNo(requestVo.getHospitalCode(),requestVo.getPatCardNo(),requestVo.getPatCardType(), requestVo.getAppId(),null);
        //Response medicalResponse = BaseService.callHumpFromInternal("yyt.base.medicalcard.by.id.get", JsonUtils.toJsonString(medicalParam));
        if (medicalCard == null) {
            throw new CallException("18010","找不到绑定卡信息 card_no=" +requestVo.getPatCardNo());
        }
        logger.info("【检验列表和明细保存线程处理-查询绑定卡信息】, yyt.base.medicalcard.by.id.get response=" + JSONObject.toJSONString(medicalCard));
        // 查询组织信息-----------------------------------------------start
        Map<String, String> orgParamMap = new HashMap<String, String>();
        orgParamMap.put("org_code", requestVo.getHospitalCode());
        logger.info("【检查列表和明细-查询组织信息】, yyt.base.branchhospital.org.list request=" + JSON.toJSONString(orgParamMap));
        Response orgResponse = BaseService.callUnderlineFromInternal("yyt.base.branchhospital.org.list", JSON.toJSONString(orgParamMap));
        logger.info("【检查列表和明细-查询组织信息】, yyt.base.branchhospital.org.list response=" + JSONObject.toJSONString(orgResponse));
        if (!"0".equals(orgResponse.getResultCode())) {
            throw new CallException("18010","找不到机构信息 by org_code=" + requestVo.getHospitalCode());
        }
        List<Org> orgList = JsonUtils.parseArray(orgResponse.getResult(), Org.class);
        if (org.springframework.util.CollectionUtils.isEmpty(orgList)) {
            throw new CallException("18010","找不到机构信息 by org_code=" + requestVo.getHospitalCode());
        }
        Org org = orgList.get(0);
        //存检验基本信息
        if (inspectListVoResponseList != null && inspectListVoResponseList.size() > 0) {
        	Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("orgCode", requestVo.getHospitalCode());
			//paramMap.put("branchHospitalCode", reportVo.getBranchHospitalCode());
			List<String> inspectIds = new ArrayList<String>();
			for (InspectListVoResponse inspect: inspectListVoResponseList) {
				inspectIds.add(inspect.getInspectId());
			}
			paramMap.put("inspectIds", inspectIds);
			List<String> existsInspectIds = inspectDao.findByOrgCodeAndInspectIds(paramMap);
			
			// 需要插入的列表
			Inspect inspect = null;
			//需要插入的详情
			List<InspectDetail> insertInspectDetailList = null;
	        for (InspectListVoResponse vo : inspectListVoResponseList) {
	        	//数据库不存在检查记录就将记录存进数据库
	        	if (!existsInspectIds.contains(vo.getInspectId())) {
	        		inspect = new Inspect();
	        		inspect.setId(PKGenerator.generateId());
	        		inspect.setOrgId(org.getId());
	        		inspect.setOrgName(org.getOrgName());
	        		inspect.setOrgCode(requestVo.getHospitalCode());
	        		inspect.setBranchId("");
	        		inspect.setBranchName("");
	        		inspect.setBranchCode(requestVo.getBranchCode());
	        		inspect.setPatId(medicalCard.getPatId());
	        		inspect.setPatName(medicalCard.getPatName());
	        		inspect.setPatSex(medicalCard.getPatSex());
	        		inspect.setPatAge(medicalCard.getPatAge());
	        		inspect.setPatMobile(medicalCard.getPatMobile());
	        		inspect.setPatAddress(medicalCard.getPatAddress());
	        		inspect.setIdCardType(medicalCard.getIdCardType());
	        		inspect.setIdCardNo(medicalCard.getIdCardNo());
	        		inspect.setMedicalCardNo(medicalCard.getMedicalCardNo());
	        		inspect.setMedicalCardType(medicalCard.getMedicalCardType());
	        		inspect.setAdmissionNo(medicalCard.getAdmissionNo());
	        		inspect.setInspectId(vo.getInspectId());
	        		inspect.setInspectName(vo.getInspectName());
	        		//检验类型 0 全部
	        		inspect.setInspectType(new Short("0"));
	        		inspect.setDeptName(vo.getDeptName());
	        		inspect.setDeptCode("");
	        		inspect.setDoctorName(vo.getDoctorName());
	        		inspect.setDoctorCode(vo.getDoctorCode());
	        		inspect.setInspectTime("".equals(vo.getInspectTime())?null:vo.getInspectTime());
	        		inspect.setVerifyDoctor(vo.getVerifyDoctor());
	        		inspect.setVerifyTime("".equals(vo.getVerifyTime())?null:vo.getVerifyTime());
	        		inspect.setInspectDoctor(vo.getInspectDoctor());
	        		inspect.setInspectDoctorCode("");
	        		inspect.setProvingTime("".equals(vo.getProvingTime())?null:vo.getProvingTime());
	        		inspect.setReportTime("".equals(vo.getReportTime())?null:vo.getReportTime());
	        		inspect.setFileAddress(vo.getFileAddress());
	        		
	        		//收集明细数据
	        		List<InspectDetailVoResponse> inspectDetailVoResponseList = vo.getInspectDetails();
	        		insertInspectDetailList = new ArrayList<InspectDetail>();
	        		InspectDetail inspectDetail = null;
	        		for(InspectDetailVoResponse inspectDetailVo : inspectDetailVoResponseList){
	        			inspectDetail = new InspectDetail();
	        			inspectDetail.setId(PKGenerator.generateId());
	        			inspectDetail.setDataInspectId(inspect.getId());
	        			inspectDetail.setItemName(inspectDetailVo.getItemName());
	        			inspectDetail.setResult(inspectDetailVo.getResult());
	        			inspectDetail.setUnit(inspectDetailVo.getUnit());
	        			inspectDetail.setRefRange(inspectDetailVo.getRefRange());
	        			inspectDetail.setAbnormal(inspectDetailVo.getAbnormal());
	        			
	        			insertInspectDetailList.add(inspectDetail);
	        		}
	        		
	        		//插入检查列表信息
	        		logger.info("要新增的检验列表=="+JsonUtils.toJsonString(inspect));
	        		inspectDao.insert(inspect); 
	        		
	        		if (CollectionUtils.isNotEmpty(insertInspectDetailList)) {
		        		//插入检查列表明细接口
		        		logger.info("要新增的检查明细=="+JsonUtils.toJsonString(insertInspectDetailList));
		        		inspectDetailDao.batchInsert(insertInspectDetailList);
	        		}
	        	}
	        }
        }
    }
}
